package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String , Method> mapping = new HashMap<>();
    static {
        initMapping();
    }
    private static void initMapping()  {
        try {
            File baseDir = new File(HandlerMapping.class.getClassLoader().getResource(".").toURI());
            File dir = new File(baseDir,"com/birdboot/controller");
            File [] subs = dir.listFiles(f -> f.getName().contains(".class"));
            for (File sub: subs
            ) {
                String fileName = sub.getName();
                String className = fileName.substring(0,fileName.indexOf("."));
                Class cls = Class.forName("com.birdboot.controller."+className);
                if(cls.isAnnotationPresent(Controller.class)){
                    Method [] methods = cls.getDeclaredMethods();
                    for (Method method:methods) {
                        if(method.isAnnotationPresent(RequestMapping.class)){
                            String value = method.getAnnotation(RequestMapping.class).value();
                            mapping.put(value,method);
                            Object obj = cls.newInstance();
//                            //cls.getMethod(method.getName(),request.getClass(),response.getClass()).invoke(obj,request,response);
//                            method.invoke(obj,request,response);
                            //return;
                        }
                    }
                }
            }
        }catch (URISyntaxException | ClassNotFoundException  | InstantiationException| IllegalAccessException e){
            e.printStackTrace();
        }
    }
    public static Method getMapping(String path) {
        return mapping.get(path);
    }

}
